package com.google.code.yargon.db;

import java.sql.*;

import com.google.code.yargon.level.Area;

public class DbTest {
	
	/**
	 * @param args
	 */
	 public static void main(String[] args) throws Exception {	
		 	 
		    Class.forName("org.sqlite.JDBC");
		    Connection conn =
		      DriverManager.getConnection("jdbc:sqlite:test.db");
		    Statement stat = conn.createStatement();
		    stat.executeUpdate("drop table if exists trap;");
		    stat.executeUpdate("create table trap (trapid, name);");
		    PreparedStatement prep = conn.prepareStatement(
		      "insert into trap values (?, ?);");
		   
		    prep.setString(1, "1");
		    prep.setString(2, "Orava");
		    prep.addBatch();
		    prep.setString(1, "2");
		    prep.setString(2, "Illu.., eiku");
		    prep.addBatch();
		    prep.setString(1, "3");
		    prep.setString(2, "Sangollinen kalanpaskaa");
		    prep.addBatch();

		    conn.setAutoCommit(false);
		    prep.executeBatch();
		    conn.setAutoCommit(true);

		    ResultSet rs = stat.executeQuery("select * from trap;");
		    while (rs.next()) {
		      System.out.println("id = " + rs.getString("trapid") + ", name = " + rs.getString("name"));
		    }
		    rs.close();
		    
		    // Objectin tallennus testi
		    stat.executeUpdate("drop table if exists object;");
		    stat.executeUpdate("create table object (id string, data blob);");
		    prep = conn.prepareStatement(
		      "insert into object values (?, ?);");
		    
		    prep.setString(1, "1");
		    prep.setObject(2, new Area(10,10));
		    prep.addBatch();
	
		    conn.setAutoCommit(false);
		    prep.executeBatch();
		    conn.setAutoCommit(true);

		    rs = stat.executeQuery("select * from object;");
		    while (rs.next()) {
		    	//Area a = (Area)rs.getObject(2);
		    	Area a = (Area) rs.getObject(2);
		    	System.out.println("id = " + rs.getString("id") + ", data =\n" +a.toString());
		    }
		    rs.close();	    
		    conn.close();
		    
		    System.out.println("Done.");
		    System.exit(0);
	 }
}
